import { http } from '@/utils/request';
import type { ApiResponse } from '@/types';

// 讨论区相关类型定义
export interface Discussion {
  id: number;
  title: string;
  content: string;
  summary?: string;
  category: string;
  is_pinned: boolean;
  view_count: number;
  like_count: number;
  created_at: string;
  updated_at?: string;
  author: {
    id: number;
    username: string;
    avatar: string;
  };
}

export interface DiscussionComment {
  id: number;
  discussion_id: number;
  user_id: number;
  content: string;
  parent_id?: number;
  like_count: number;
  created_at: string;
  user: {
    id: number;
    username: string;
    avatar: string;
  };
  replies?: DiscussionComment[];
}

export interface DiscussionListResponse {
  discussions: Discussion[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_page: number;
  };
}

export interface DiscussionCommentListResponse {
  comments: DiscussionComment[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_page: number;
  };
}

export interface DiscussionQuery {
  page?: number;
  page_size?: number;
  category?: string;
  search?: string;
}

export interface DiscussionCommentQuery {
  page?: number;
  page_size?: number;
}

export interface CreateDiscussionRequest {
  title: string;
  content: string;
  category?: string;
}

export interface UpdateDiscussionRequest {
  title?: string;
  content?: string;
  category?: string;
}

export interface CreateDiscussionCommentRequest {
  content: string;
  parent_id?: number;
}

export const discussionApi = {
  // 获取讨论列表
  getDiscussions(params?: DiscussionQuery): Promise<ApiResponse<DiscussionListResponse>> {
    return http.get('/v1/discussions', { params });
  },

  // 获取讨论详情
  getDiscussionDetail(discussionId: number): Promise<ApiResponse<Discussion>> {
    return http.get(`/v1/discussions/${discussionId}`);
  },

  // 创建讨论
  createDiscussion(data: CreateDiscussionRequest): Promise<ApiResponse<{ id: number }>> {
    return http.post('/v1/discussions', data);
  },

  // 更新讨论
  updateDiscussion(discussionId: number, data: UpdateDiscussionRequest): Promise<ApiResponse<void>> {
    return http.put(`/v1/discussions/${discussionId}`, data);
  },

  // 删除讨论
  deleteDiscussion(discussionId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/discussions/${discussionId}`);
  },

  // 获取讨论评论
  getDiscussionComments(discussionId: number, params?: DiscussionCommentQuery): Promise<ApiResponse<DiscussionCommentListResponse>> {
    return http.get(`/v1/discussions/${discussionId}/comments`, { params });
  },

  // 创建讨论评论
  createDiscussionComment(discussionId: number, data: CreateDiscussionCommentRequest): Promise<ApiResponse<{ id: number }>> {
    return http.post(`/v1/discussions/${discussionId}/comments`, data);
  },
};
